package actions;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import services.UserService;
import t4p.model.User;

/**
 * Servlet implementation class UnfollowUser
 */
@WebServlet("/unfollowUser")
public class UnfollowUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username = request.getParameter("username");
		HttpSession session = request.getSession(true);
		
		User loggedUser = (User)session.getAttribute("loggedUser");
		User currentUser = (User) UserService.getInstace().getUserByUsername(username);	
		
		if (UserService.getInstace().removeFollowing(loggedUser, currentUser)){
			if(UserService.getInstace().removeFollower(loggedUser, currentUser))
				response.sendRedirect(response.encodeRedirectURL("/aaarrgh/pages/foreignProfile.jsp?username=" + username) );
		}else{
			response.sendRedirect(response.encodeRedirectURL("/aaarrgh/pages/foreignProfile.jsp?error=1"));	
		}
		
	}

}
